<?php
include_once 'fun.php';
include_once 'islogin.php';
$_SESSION['isadmin']=isset($_SESSION['isadmin'])?$_SESSION['isadmin']:'';
  if ($_SESSION['isadmin']!=0&&$_SESSION['isadmin']!=-1) {
      header('Refresh:1;url=shop.php');
      die("请以销售身份登录");
  }
    //var_dump($_FILES);
    $Name = trim($_POST['Name']);
    $counternum = ($_POST['counternum']!='')?$_POST['counternum']:0;
    $price =($_POST['price']!='')?trim($_POST['price']):0;
    $soldnum =($_POST['soldnum']!='')?trim($_POST['soldnum']):0;
    $id=(int)$_POST['id'];
    //var_dump($id);
   // $pic='pics/default.PNG';
    if(empty($Name))
    {
    header('Refresh:0;url=sell.php');
    die("商品名不能为空");
    }
   
    else
    {
        $con=connect();
        $sql = "select productid from product where Name like '$Name' ";
        $res=query($sql,$con);
        $a=mysqli_fetch_row($res);
        if($res->num_rows>1||($res->num_rows==1&&$a[0]!=$id)){
            alertMes("商品名不能相同",'sell.php');
            exit;
        }
        $sql = "select stocknum,counternum,soldnum from product where productid=$id ";
        $res=query($sql,$con);
        $r=mysqli_fetch_row($res);
        $stocknum=$r[0];
        $counter=$r[1];
        $sold=$r[2];
        //var_dump($stocknum);
       // var_dump($counter);
       if($price<0)
        {
            alertMes("售价不能小于零",'sell.php');
            exit;
        }
       if($counternum<0||$soldnum<0)
        {
            alertMes("柜存或销量不能小于零",'sell.php');
            exit;
        }
        if($counternum>$stocknum+$counter)
        {
            alertMes("超过库存最大限制",'sell.php');
            exit;
        }
        if($soldnum>$counter+$sold)
        {
            alertMes("销售最大限制",'sell.php');
            exit;
        }
        //var_dump($stocknum+$counternum);
        $sql = "update product set Name='{$Name}',counternum=$counternum-($soldnum-$sold),soldnum={$soldnum},incomeoverall=$soldnum*$price,price={$price},stocknum=($stocknum+$counter)-$counternum where productid={$id}";
        query($sql,$con);
        echo '保存成功';
        
   header('Refresh:0;url=sell.php');
    
    }
    
    
?>